<template>

    <div>
      <el-button @click="initWebSocket">查看服务日志</el-button>
      <el-button @click="websocketclose">关闭服务日志</el-button>
      <!-- <p>xxxx{{WSURL}}</p> -->
    </div>
  
    <el-input v-model="sendMsg"></el-input>
    <el-button @click="websocketSend(taskList)">发送</el-button>
    <p>子组件接收到的taskList:{{ taskList }}</p>
  
    <div id="logContainer" v-show="logArray">
      <h3>后端服务日志</h3>
      <div id="showlog"></div>
  </div>
  
  </template>
  
  <script>
  const WSURL = import.meta.env.VITE_TASK_STATUS_URL
  
  export default {
    name: 'wstest',
    // 组件退出挂载（切换页面、刷新等）时触发
    unmounted() {
      // 退出组件时，关闭 websocket 
      this.unmountWebsocket()
    },
    props: ['taskList'],
    data() {
      return {
        // 日志区域显示开关
        logArray: false,
        // 发送的消息
        sendMsg: [
            "8dbe5c27-93cf-4516-a9b1-6019fbd97d4a",
            "6dd7f10c-9a88-415d-8905-2ea0e31dbb8d",
            "13e4f925-fde3-4693-bcdf-6dec5813f0e9",
            "88123f89-4305-4590-82db-1d83c40803bc"
        ],
        
      }
    },
    methods: {
      //初始化weosocket
      initWebSocket() {
        if (typeof WebSocket === "undefined") {
          alert("您的浏览器不支持WebSocket");
          return false;
        }
        const wsuri = `${WSURL}` // websocket地址
        console.log("wsuri:", wsuri, "WSURL:", WSURL);
        console.log("mode:", import.meta.env.MODE);
   
        this.websock = new WebSocket(wsuri);
        this.websock.onopen = this.websocketonopen;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      //连接成功
      websocketonopen() {
        console.log("WebSocket连接成功");
        this.logArray = true;
        // this.websock.send('send massage')
        // console.log('发送消息');
        // 添加心跳检测，每30秒发一次数据，防止连接断开（这跟服务器的设置有关，如果服务器没有设置每隔多长时间不发消息断开，可以不进行心跳设置）
        // let self = this;
        // this.timer = setInterval(() => {
        //   try {
        //     self.websock.send('test')
        //     console.log('发送消息');
        //   }catch(err){
        // console.log('断开了：' + err);
        //     self.connection()
        //   }
        // }, 30000)
      },
      // 发送消息
      websocketSend(msg){
        console.log("发送消息: ", msg);
        this.websock.send(msg.toString())
      },
      //接收后端返回的数据，可以根据需要进行处理
      websocketonmessage(e) {
        var vm = this;
        console.log("收到的消息：", e.data);
        //添加到页面中
        const pDom = document.createElement('p')
        pDom.innerHTML = e.data
        
        document.querySelector('#logContainer div').append(pDom)
        var element = document.getElementById("showlog");
        element.scrollTop = element.scrollHeight;
        //  文字居左
        pDom.style.textAlign="left"
        // 文字离左边 10px
        pDom.style.paddingLeft="10px"
      },
      //连接建立失败重连
      websocketonerror(e) {
        console.log(`连接失败的信息：`, e);
        this.initWebSocket(); // 连接失败后尝试重新连接
      },
      //关闭连接
      websocketclose(e) {
        var vm = this;
        // console.log('websocket状态：', vm.websock.readyState , typeof(vm.websock.readyState));
        if (vm.websock.readyState === 1){
          document.getElementById('showlog').innerHTML = "";
        vm.websock.close()
        this.logArray = false;
        console.log("断开连接", e);
        }else if(vm.websock.readyState === 0){
          console.log('websocker没有连接哟，不用关闭');
        }else{
          console.log('websocket可能正在关闭，等等看，或者出错了吧');
        }
      },
    //关闭websocket
      closeWebsocket(){
          if(this.websock){
              this.websock.close();
              let _this=this
              this.websock.onclose = function(evt) {
                   console.log("websocket已关闭"); 
              };
          }
      },
   //关闭websocket(退出组件时)
    unmountWebsocket(){
      if(this.websock){
        this.websock.close();
        this.logArray = false;
        // let _this=this
        this.websock.onclose = function(evt) {
          console.log("websocket已关闭"); 
        };
      }
    }
    },
  }
  
  
  </script>
  
  <style scoped>
  #showlog{
    background-color: black;
    color: white;
    width: 1200px;
    height: 600px;
    overflow: auto;
    word-break: break-word;
    margin: 0 auto;
  }
  </style>
  
  
  